package org.biubiu0002.baiblog.core.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;

/**
 * @Author: biubiu0002
 * @Date: 2022-05-05 22:56
 **/
@Component
public class JwtTokenUtil {

    @Value("${jwt.secret:hahamysecret}")
    private String secret;

    @Value("${jwt.expiration:3000000}")
    private Long expiration;

    private static String SECRET;
    private static Long EXPIRATION;


    /**
     * 根据payload、用户名、过期时间生成token
     * @param claims 附加信息
     * @param username 用户名
     * @return token
     */
    public static String generateToken(Map<String,Object> claims,String username){
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .claim("username",username)
                .addClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .compact();
    }



    public static Claims parseJwtHS256(String jwt){
        return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwt).getBody();
    }

    @PostConstruct
    public void init(){
        SECRET=this.secret;
        EXPIRATION=this.expiration;

    }
}
